/**
 * Description: UDP广播发送端
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>

#define N 100

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage %s <broadcast ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    char buff[N] = {0};

    // 设置允许发送广播
    int is_on = 1;
    if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &is_on, sizeof(is_on))) {
        perror("setsockopt");
        return 0;
    }

    struct sockaddr_in sendaddr;
    sendaddr.sin_family = AF_INET;
    sendaddr.sin_port = htons(atoi(argv[2]));
    sendaddr.sin_addr.s_addr = inet_addr(argv[1]);

    while(1) {
        printf("send broadcast:");
        fgets(buff, N, stdin);
        buff[strlen(buff) - 1] = '\0';

        if (-1 == sendto(sockfd, buff, N, 0, (struct sockaddr *)&sendaddr, 
                sizeof(struct sockaddr)))
        {
            perror("sendto");
            return 0;
        }
    }


    return 0;
}
